package com.guangbao.service.impl;

import java.util.List;

import com.google.gson.Gson;
import com.guanbao.entity.User;
import com.guangbao.dao.UserDao;
import com.guangbao.dao.impl.UserDaoImpl;
import com.guangbao.service.UserService;
import com.guangbao.utils.JedisUtil;

public class UserServiceImpl implements UserService {
	private UserDao userDao = new UserDaoImpl();

	@Override
	public User getUserByUsername(String username) {
		return userDao.queryUserByUsername(username);
	}

	@Override
	public User getUserById(Integer id) {
		Gson gson = new Gson();
		String userStr = JedisUtil.get("user"+id);
		if(userStr == null || userStr.isEmpty()) {
			User user = userDao.queryUserById(id);
			if(user != null) {
				JedisUtil.set("user"+id, gson.toJson(user));
				return user;
			}
		}else {
			return gson.fromJson(userStr, User.class);
		}
		return null;
	}

	@Override
	public Boolean saveUser(User user) {
		int flag = userDao.insertUser(user);
		return flag == -1?false:true;
	}

	@Override
	public Boolean editUser(User user) {
		int flag = userDao.updateUser(user);
		if(flag != -1) {
			user = userDao.queryUserById(user.getId());
			if(user != null) {
				Gson gson = new Gson();
				JedisUtil.set("user"+user.getId(), gson.toJson(user));
			}
		}
		return flag == -1?false:true;
	}

	@Override
	public List<User> getAllUser() {
		return this.userDao.queryAllUser();
	}

	@Override
	public Boolean removeUser(Integer id) {
		int flag = userDao.deleteUser(id);
		if(flag !=-1) {
			JedisUtil.del("user"+id);
		}
		return flag == -1?false:true;
	}

}
